package org.todd.healthreport.service.Impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.todd.healthreport.service.IHealthReportService;
import org.todd.healthreport.service.WeatherService;
import org.todd.healthreport.util.EmailUtil;

import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class HealthReportServiceImpl extends BaseChromeDriver implements IHealthReportService {

    @Value("${healthReport}")
    private String healthReportUrl;

    @Value(("${userIdCardAndEmail}"))
    private String userInfoList;



    @Value("${weatherKey}")
    private String weatherKey;

    @Value("${weatherCity}")
    private String weatherCity;

    @Autowired
    private WeatherService weatherService;

    private Map<String, String> userMap = new HashMap<>();

    ChromeDriver chrome = null;

    @Autowired
    private EmailUtil emailUtil;

    @Override
    public void healthReport() {
        System.out.println("健康报备");
        String weather = getWeather(weatherKey, weatherCity);
        getUserMap();
        Set<String> IdCards = userMap.keySet();
        for (String idCard : IdCards) {
            String name = reportHandel(idCard).concat("已健康报备");
            //发送提醒邮件
            emailUtil.sendEmail(userMap.get(idCard), name, weather);
        }
    }

    @Override
    public String reportHandel(String idCard) {
        login(idCard);
        doReport();
        return getReportInfo();
    }

    private void login(String idCard) {
        chrome = super.getChromeDriver();
        chrome.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        chrome.get(healthReportUrl);
        chrome.switchTo().alert().dismiss();
        WebElement idCardInput = chrome.findElementByClassName("mint-field-core");
        idCardInput.sendKeys(idCard);
        WebElement loginBtn = chrome.findElementByClassName("login-btn");
        loginBtn.click();
    }


    private void doReport() {
        WebDriverWait wait = new WebDriverWait(chrome, 10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.linkText("申报")));
        WebElement submit = chrome.findElementByClassName("sub-btn");
        submit.click();
        System.out.println("报备完成");
        WebElement myBut = chrome.findElementByXPath("/html/body/div[1]/div[2]/div[2]/a[3]/div[2]");
        myBut.click();
    }

    private String getReportInfo() {
        String temp = "";
       WebElement project = chrome.findElementByXPath("/html/body/div[1]/div[2]/div[1]/div/div[6]/div[3]");
        WebElement name = chrome.findElementByXPath("/html/body/div[1]/div[2]/div[1]/div/div[1]/div[3]");
        temp = project.getText() + "的" + name.getText();
        WebElement text = chrome.findElementByXPath("/html/body/div[1]/div[2]/div[1]/div/div[8]/div[3]/div");
        if (text.getText().equals("已报备")) {
            System.out.println(temp + "报备完成");
        } else {
            temp = "报备失败";
            System.out.println("报备失败");
        }
        chrome.close();
        return temp;
    }


    private void getUserMap() {
        if (userMap.isEmpty()) {
            String[] split = userInfoList.split(",");
            for (String userInfo : split) {
                String[] user = userInfo.split("-");
                userMap.put(user[0], user[1]);
            }
        } else {
            userMap.clear();
            getUserMap();
        }
    }

    public String getWeather(String key, String city) {
        StringBuffer weatherInfo = new StringBuffer();
        JSONObject jsonObj = weatherService.getWeather(key, city);
        JSONObject realtime = jsonObj.getJSONObject("realtime");
        JSONArray futures = jsonObj.getJSONArray("future");
        weatherInfo.append(city + "现在" + realtime.getString("info") + "," + realtime.getString("direct") + realtime.getString("power") + "," + realtime.getString("temperature") + "℃.");
        JSONObject today = futures.getJSONObject(0);
        weatherInfo.append(city + "今天" + today.getString("weather") + "," + today.getString("direct") + "," + today.getString("temperature"));
        return weatherInfo.toString();
    }

}
